package com.zaoke.web.service.user.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.util.CollectionUtils;

import com.zaoke.web.bo.query.user.UserQuery;
import com.zaoke.web.bo.user.User;
import com.zaoke.web.bo.zone.Zone;
import com.zaoke.web.dao.user.UserDao;
import com.zaoke.web.dao.zone.ZoneDao;
import com.zaoke.web.service.user.UserService;

public class UserServiceImpl implements UserService {
	
	private UserDao userDao;
	
	private ZoneDao zoneDao;
	

	public User getUserInfo(long userid){
		return userDao.getUserInfo(userid);
	}

	public User autoRegisterUser(String name){
		if(StringUtils.isNotBlank(name)){
			User user = new User();
			user.setUserName(name);
			user.setState(User.STATE_AUTO);
			Date now = new Date();
			user.setRegisterTime(now);
			user.setModTime(now);
			
			long userid = userDao.addAutoUser(user);
			if(userid > 0){
				user.setUserId(userDao.addAutoUser(user));
				return user;
			}
		}
		return null;
	}

	@Override
	public List<User> queryUserInfo(UserQuery query) {
		List<User> users = userDao.queryUserInfo(query);
		
		Set<Long> zoneids = new HashSet<Long>(); 
		
		if(users!=null && users.size()>0)
		{
			for(User user : users)
			{
				zoneids.add(user.getZoneId());
			}
		}
		List<Long> zoneidsb = new ArrayList<Long>();
		zoneidsb.addAll(zoneids);
		List<Zone> zones = new ArrayList<Zone>();
		if(!CollectionUtils.isEmpty(zoneidsb))
			zones = zoneDao.findZoneByIds(zoneidsb);
		
		Map<Long,String> map = new HashMap<Long, String>();
		if(zones!=null && zones.size()>0)
		{
			for(Zone zone : zones)
			{
				map.put(zone.getId(), zone.getName());
			}
		}
		if(users!=null && users.size()>0)
		{
			for(User user : users)
			{
				String zoneName = map.get(user.getZoneId());
				if(zoneName==null || "".equals(zoneName))
				{
					zoneName="未设置";
				}
				user.setZoneName(zoneName);
			}
		}
		
		return users;
	}

	@Override
	public Map<Long, User> getUserInfos(Set<Long> userIds) {
		return userDao.getUserInfos(userIds);
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public void setZoneDao(ZoneDao zoneDao) {
		this.zoneDao = zoneDao;
	}
}
